//
//  YXManagerScrollView.m
//  MockProject
//
//  Created by FanYu on 23/8/2016.
//  Copyright © 2016 niuzhaowang. All rights reserved.
//

#import "YXManagerScrollView.h"
#import "Config.h"
#import "YXDownloadingTableViewCell.h"
#import "YXDownloadedTableViewCell.h"
#import "YXTableSectionHeaderView.h"
#import "YXTaskManager.h"
#import "YXUserDefault.h"

@interface YXManagerScrollView () <UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, YXTableSectionHeaderViewDelegate, YXDownloadingTableViewCellDelegate>

@property (nonatomic, strong) UITableView *downloadingTableView;
@property (nonatomic, strong) UITableView *downloadedTableView;
@property (nonatomic, strong) NSMutableArray *selectedCellTag;
@property (nonatomic, strong) NSArray *downloadingArray;
@property (nonatomic, strong) NSArray *downloadedArray;
@property (nonatomic, strong) NSArray *currentDownloadingArray;
@property (nonatomic, strong) UILabel *downloadingHitLabel;
@property (nonatomic, strong) UILabel *downloadedHitLabel;
@property (nonatomic, assign) BOOL isEditing;
@property (nonatomic, assign) BOOL isSelectAll;
@property (nonatomic, assign) BOOL isNotification;
@property (nonatomic, assign) BOOL didPauseAll;

@end


@implementation YXManagerScrollView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

#pragma mark - Setup UI
- (void)setupUI {
    // self
    self.contentSize = CGSizeMake(SCREEN_WIDTH * 2, 0);
    self.bounces = NO;
    self.pagingEnabled = YES;
    self.delegate = self;
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
    
    // downloading
    self.downloadingTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, self.bounds.size.width, self.bounds.size.height - 110) style:UITableViewStylePlain];
    self.downloadingTableView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    self.downloadingTableView.rowHeight = 80;
    self.downloadingTableView.delegate = self;
    self.downloadingTableView.dataSource = self;
    self.downloadingTableView.tableFooterView = [[UIView alloc] init];
    self.downloadingTableView.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
    [self addSubview:self.downloadingTableView];
    
    [self.downloadingTableView registerNib:[UINib nibWithNibName:@"YXDownloadingTableViewCell" bundle:nil] forCellReuseIdentifier:@"YXDownloadingTableViewCell"];
    [self.downloadingTableView registerClass:[YXTableSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"YXTableSectionHeaderView"];
    
    // downloaded
    self.downloadedTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.bounds.size.width, 44, self.bounds.size.width, self.bounds.size.height - 110) style:UITableViewStylePlain];
    self.downloadedTableView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    self.downloadedTableView.rowHeight = 80;
    self.downloadedTableView.delegate = self;
    self.downloadedTableView.dataSource = self;
    self.downloadedTableView.allowsMultipleSelectionDuringEditing = YES;
    self.downloadedTableView.tableFooterView = [[UIView alloc] init];
    self.downloadedTableView.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
    [self addSubview:self.downloadedTableView];
    
    [self.downloadedTableView registerNib:[UINib nibWithNibName:@"YXDownloadedTableViewCell" bundle:nil] forCellReuseIdentifier:@"YXDownloadedTableViewCell"];
    [self.downloadedTableView registerClass:[YXTableSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"YXTableSectionHeaderView"];
    
    // editign status
    self.isEditing = NO;
    
    self.isSelectAll = NO;
    
    self.isNotification = NO;
    
    self.didPauseAll = NO;
    
    // data
    [self loadTaskData];
}

- (void)loadTaskData {
    self.downloadingArray = [YXTaskManager getTasksForInProcess:NO];
    self.downloadedArray = [YXTaskManager getTasksWithStatus:YXTaskStatusDownloaded byTimeline:YES];
}


#pragma mark - Action For Task
- (void)updateSpeed:(NSString *)speed withUID:(NSString *)uid {
    [self updateCellWithUID:uid foundCell:^(YXDownloadingTableViewCell *cell) {
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.speedLabel.text = speed;
        });
    }];
}

- (void)updateProgress:(NSProgress *)progress withUID:(NSString *)uid {
    [self updateCellWithUID:uid foundCell:^(YXDownloadingTableViewCell *cell) {
        NSString *sizePercent = [NSString stringWithFormat:@"%lld / %lldM", progress.completedUnitCount / 1024 / 1024, progress.totalUnitCount / 1024 / 1024];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.progress = progress.fractionCompleted;
            cell.sizeLabel.text = sizePercent;
        });
    }];
}

- (void)downloadFinishedForTask:(NSString *)uid {
    [self updateCellWithUID:uid foundCell:^(YXDownloadingTableViewCell *cell) {
        NSIndexPath *indexPath = [self.downloadingTableView indexPathForCell:cell];
        [self loadTaskData];
        YXTableSectionHeaderView *headerView = (YXTableSectionHeaderView *)[self.downloadingTableView headerViewForSection:0];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.downloadingTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
            [headerView updateTaskAmount:YXDownloadingSectionHeader taskAmount:[YXTaskManager getTasksWithStatus:YXTaskStatusDownloading byTimeline:YES].count];
            [self.downloadedTableView reloadData];
        });
    }];
}

- (void)downloadFailedForTask:(NSString *)uid {
    [self updateCellWithUID:uid foundCell:^(YXDownloadingTableViewCell *cell) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateCellButton:cell status:@"Failed"];
            cell.speedLabel.text = @"";
            cell.status = [NSNumber numberWithInteger:YXTaskStatusFailed];
        });
    }];
}

- (void)changeTaskStatusToDownloadingWithUID:(NSString *)uid {
    [self updateCellWithUID:uid foundCell:^(YXDownloadingTableViewCell *cell) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateCellButton:cell status:@"Downloading"];
        });
    }];
}

- (void)changeTaskStatusToWaitingWithUID:(NSString *)uid {
    [self updateCellWithUID:uid foundCell:^(YXDownloadingTableViewCell *cell) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateCellButton:cell status:@"Waiting"];
        });
    }];
}

- (void)reachabilityChangedWithStatus:(NSString *)status {
    if ([status isEqualToString:@"PauseAll"]) {
        for (NSInteger row = 0; row < [self.downloadingTableView numberOfRowsInSection:0]; row++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
            YXDownloadingTableViewCell *cell = [self.downloadingTableView cellForRowAtIndexPath:indexPath];
            [self updateCellButton:cell status:@"Pause"];
        }
    }
}


#pragma mark - Helper
- (void)isShowDownloadingHitLabel:(BOOL)isShow {
    if (isShow) {
        self.downloadingHitLabel.text = @"您目前还没有下载任务哦~";
        self.downloadingHitLabel.textColor = [UIColor blackColor];
        self.downloadingHitLabel.hidden = NO;
        [self addSubview:self.downloadingHitLabel];
        
        [self.downloadingHitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
        }];
        
    } else {
        self.downloadingHitLabel.hidden = YES;
        [self.downloadingHitLabel removeFromSuperview];
    }
}

- (void)isShowDownloadedHitLable:(BOOL)isShow {
    if (isShow) {
        self.downloadedHitLabel.text = @"您还没有下载记录哦~";
        self.downloadedHitLabel.textColor = [UIColor blackColor];
        self.downloadedHitLabel.hidden = NO;
        [self addSubview:self.downloadedHitLabel];
        
        [self.downloadedHitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.mas_centerX).offset(self.bounds.size.width);
            make.centerY.equalTo(self.mas_centerY);
        }];
    
    } else {
        self.downloadedHitLabel.hidden = YES;
        [self.downloadedHitLabel removeFromSuperview];
    }
}

- (void)updateCellWithUID:(NSString *)uid foundCell:(void (^)(YXDownloadingTableViewCell *))cellBlock {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        for (NSInteger row = 0; row < [self.downloadingTableView numberOfRowsInSection:0]; row++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
            YXDownloadingTableViewCell *cell = [self.downloadingTableView cellForRowAtIndexPath:indexPath];
            if ([cell.taskModel.uid isEqualToString:uid]) {
                cellBlock(cell);
            }
        }
    });
}

- (void)updateCellButton:(YXDownloadingTableViewCell *)cell status:(NSString *)status {
    if ([status isEqualToString:@"Downloading"] || [status isEqualToString:@"Redownload"]) {
        [cell.actionButton setImage:[UIImage imageNamed:@"下载中下载"] forState:UIControlStateNormal];
        [cell.actionButton setImage:[UIImage imageNamed:@"下载中icon点击态"] forState:UIControlStateHighlighted];
        [cell.actionButton setTitle:@" 下载中" forState:UIControlStateNormal];
    } else if ([status isEqualToString:@"Pause"]) {
        [cell.actionButton setImage:[UIImage imageNamed:@"已暂停icon正常态"] forState:UIControlStateNormal];
        [cell.actionButton setImage:[UIImage imageNamed:@"已暂停icon点击态"] forState:UIControlStateHighlighted];
        [cell.actionButton setTitle:@" 已暂停" forState:UIControlStateNormal];
    } else if ([status isEqualToString:@"Waiting"]) {
        [cell.actionButton setImage:[UIImage imageNamed:@"等待中icon正常态"] forState:UIControlStateNormal];
        [cell.actionButton setImage:[UIImage imageNamed:@"等待中icon点击态"] forState:UIControlStateHighlighted];
        [cell.actionButton setTitle:@" 等待中" forState:UIControlStateNormal];
    } else if ([status isEqualToString:@"Failed"]) {
        [cell.actionButton setImage:[UIImage imageNamed:@"下载失败icon正常态"] forState:UIControlStateNormal];
        [cell.actionButton setImage:[UIImage imageNamed:@"下载失败icon点击态"] forState:UIControlStateHighlighted];
        [cell.actionButton setTitle:@" 下载失败" forState:UIControlStateNormal];
    } else if ([status isEqualToString:@"Prepare"]) {
        [cell.actionButton setImage:[UIImage imageNamed:@"等待中icon正常态"] forState:UIControlStateNormal];
        [cell.actionButton setImage:[UIImage imageNamed:@"等待中icon点击态"] forState:UIControlStateHighlighted];
        [cell.actionButton setTitle:@" 准备中" forState:UIControlStateNormal];
    }
}

- (void)updateAllDownloadTaskStatus:(NSString *)status {

    BOOL isPause = [status isEqualToString:@"Pause"];
    
    YXTableSectionHeaderView *headerView = (YXTableSectionHeaderView *)[self.downloadingTableView headerViewForSection:0];
    
    // Pause all
    if (isPause) {
        self.didPauseAll = YES;
        
        // save current downloading tasks
        self.currentDownloadingArray = [YXTaskManager getTasksWithStatus:YXTaskStatusDownloading byTimeline:NO];
        
        // change all status to pause
        NSArray *inProcess = [YXTaskManager getTasksForInProcessWithoutFailed:NO];
        for (DownloadTask *task in inProcess) {
            [YXTaskManager updateTaskStatus:YXTaskStatusPause withUID:task.uid.integerValue];
        }
        
        // push notification to stop downloading tasks
        [[NSNotificationCenter defaultCenter] postNotificationName:YXTaskStatusChangedNotification object:nil userInfo:@{@"status" : @"PauseAll"}];
        
        // update each cell to last status
        for (NSInteger row = 0; row < [self.downloadingTableView numberOfRowsInSection:0]; row++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
            YXDownloadingTableViewCell *cell = [self.downloadingTableView cellForRowAtIndexPath:indexPath];
            NSString *taskUID = [NSString stringWithFormat:@"%ld", cell.actionButton.tag];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (cell.status != [NSNumber numberWithInteger:YXTaskStatusFailed]) {
                    cell.speedLabel.text = @"";
                    [YXTaskManager updateTaskSizePercent:cell.sizeLabel.text withUID:taskUID];
                    [YXTaskManager updateTaskProgressPercent:cell.progress withUID:taskUID];
                    [self updateCellButton:cell status:status];
                }
            });
        }
        
        // update header
        dispatch_async(dispatch_get_main_queue(), ^{
            [headerView updateTaskAmount:YXDownloadingSectionHeader taskAmount:0];
            [headerView setSectionHeaderType:YXDownloadingSectionHeader isDownloadingAll:NO];
        });

    }
    // start all
    else {
        self.didPauseAll = NO;
        //empty
        //self.currentDownloadingArray = nil;
        
        // notificaiton to handle start tasks in queue
        [[NSNotificationCenter defaultCenter] postNotificationName:YXTaskStatusChangedNotification object:nil userInfo:@{@"status" : @"StartAll"}];
        
        // update header
        NSInteger taskNum = [YXTaskManager getTasksWithStatus:YXTaskStatusDownloading byTimeline:NO].count;
        dispatch_async(dispatch_get_main_queue(), ^{
            [headerView updateTaskAmount:YXDownloadingSectionHeader taskAmount:taskNum];
            [headerView setSectionHeaderType:YXDownloadingSectionHeader isDownloadingAll:YES];
        });
    }
}

- (NSIndexPath *)getCellIndexPathWithSender:(UIButton *)sender {
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.downloadingTableView];
    NSIndexPath *indexPath = [self.downloadingTableView indexPathForRowAtPoint:buttonPosition];
    return indexPath;
}

- (void)handleDownloadingButtonTapped:(UIButton *)sender {
    NSString *status = [[NSString alloc] init];
    NSString *taskUID = [NSString stringWithFormat:@"%ld", sender.tag];
    NSIndexPath *indexPath = [self getCellIndexPathWithSender:sender];
    YXDownloadingTableViewCell *cell = [self.downloadingTableView cellForRowAtIndexPath:indexPath];
    YXTableSectionHeaderView *headerView = (YXTableSectionHeaderView *)[self.downloadingTableView headerViewForSection:0];
    
    self.currentDownloadingArray = [YXTaskManager getTasksWithStatus:YXTaskStatusDownloading byTimeline:NO];
    
    // update task status
    switch ([YXTaskManager getTaskStatusWithUID:sender.tag]) {
        case YXTaskStatusDownloading:
            [YXTaskManager updateTaskStatus:YXTaskStatusPause withUID:sender.tag];
            status = @"Pause";
            break;
        case YXTaskStatusPause:
            [YXTaskManager updateTaskStatus:YXTaskStatusDownloading withUID:sender.tag];
            status = @"Downloading";
            break;
        case YXTaskStatusWaiting:
            status = @"WaitingToDownloading";
            break;
        case YXTaskStatusFailed:
            status = @"Redownload";
            break;
        default:
            status = @"NA";
            break;
    }
    
    NSInteger downloadingNum = [YXUserDefault currentDownloadingNumber];
    // 当前任务数已达最大值 点击非在之前下载队列的任务
    if ([status isEqualToString:@"Downloading"] && downloadingNum >= [YXUserDefault maxSimultaneouslyNumber].integerValue) {
        if ([self isInCurrentDownloadingArrayForUID:taskUID]) {
            status = @"Waiting";
            [YXTaskManager updateTaskStatus:YXTaskStatusWaiting withUID:taskUID.integerValue];
        }
    }
    // 当前任务数已达最大值 点击下载失败的任务
    else if ([status isEqualToString:@"Redownload"] && downloadingNum >= [YXUserDefault maxSimultaneouslyNumber].integerValue) {
            status = @"Waiting";
            [YXTaskManager updateTaskStatus:YXTaskStatusWaiting withUID:taskUID.integerValue];
    } else {
        // push notification to let pre-vc contorl tasks
        [[NSNotificationCenter defaultCenter] postNotificationName:YXTaskStatusChangedNotification object:nil userInfo:@{@"uid" : taskUID, @"status" : status}];
    }
    
    // update UI
    NSInteger downloadingTasksNum = [YXTaskManager getTasksWithStatus:YXTaskStatusDownloading byTimeline:YES].count;
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([status isEqualToString:@"Pause"]) {
            // save last size and percnet
            cell.speedLabel.text = @"";
            [YXTaskManager updateTaskSizePercent:cell.sizeLabel.text withUID:taskUID];
            [YXTaskManager updateTaskProgressPercent:cell.progress withUID:taskUID];
        }
        
        [self updateCellButton:cell status:status];
        
        [headerView updateTaskAmount:YXDownloadingSectionHeader taskAmount:downloadingTasksNum];
        [headerView setSectionHeaderType:YXDownloadingSectionHeader isDownloadingAll:downloadingTasksNum != 0];
    });
}

- (BOOL)isInCurrentDownloadingArrayForUID:(NSString *)uid {
    for (DownloadTask *task in self.currentDownloadingArray) {
        if ([task.uid isEqualToString:uid]) {
            return YES;
        }
    }
    return NO;
}

- (void)handleTaskSelectionForEditing:(BOOL)isEidting {
    for (int row = 0; row < self.downloadedArray.count; row++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        YXDownloadedTableViewCell *cell = [self.downloadedTableView cellForRowAtIndexPath:indexPath];
        cell.selectionImageView.highlighted = NO;
        cell.selectionImageView.hidden = isEidting;
        cell.isSelected = NO;
    }

    if (self.isEditing) {
        [self.selectedCellTag removeAllObjects];
    } else {
        [self.yxDelegate selectedCellAmount:0];
    }
}

#pragma mark - YXDownloadingTableViewCellDelegate
- (void)downloadingCellButtonTapped:(UIButton *)sender {
    if ([YXUserDefault reachability] == NotReachable) {
        [self.yxDelegate showAlertWithTitle:@"当前没有网络哦～"];
    } else if ([YXUserDefault reachability] == ReachableViaWWAN && [YXUserDefault onlyDownloadOnWiFi]) {
        [self.yxDelegate showAlertWithTitle:@"无法手动启动，请去‘设置-通用设置’里进行设置"];
    } else if ([YXUserDefault reachability] == ReachableViaWiFi) {
        [self handleDownloadingButtonTapped:sender];
    } else if ([YXUserDefault reachability] == ReachableViaWWAN && ![YXUserDefault onlyDownloadOnWiFi]) {
        [self handleDownloadingButtonTapped:sender];
    }
}


#pragma mark - YXTableSectionHeaderViewDelegate
- (void)headerButtonTapped:(UIButton *)sender {
    // for downloaedTableView to use to hide/show bottom view
    [self.yxDelegate sectionHeaderButtonTapped:sender sectionHeaderType:sender.tag];
    
    if (sender.tag == YXDownloadingSectionHeader) {
        if ([sender.titleLabel.text isEqualToString:@" 全部暂停"]) {
            [self updateAllDownloadTaskStatus:@"Pause"];
        }
        else {
            [self updateAllDownloadTaskStatus:@"Downloading"];
        }
    } else if (sender.tag == YXDownloadedSectionHeader) {
        [self handleTaskSelectionForEditing:self.isEditing];
        self.isEditing = !self.isEditing;
    }
}


#pragma mark - Downloaded TableView Actions
- (void)commitDeleting {
    for (NSString *tagStr in self.selectedCellTag) {
        [YXTaskManager updateTaskStatus:YXTaskStatusNA withUID:tagStr.integerValue];
        [YXTaskManager updateTaskProgressPercent:0.0 withUID:tagStr];
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:[YXTaskManager getTaskFilePathWithUID:tagStr] error:&error];
        if (error) {
            NSLog(@"DeleteFileError: %@", error);
        }
    }
    [self loadTaskData];
    [self.downloadedTableView reloadData];
    
    // reset temp
    [self.selectedCellTag removeAllObjects];
    
    // update section header number
    YXTableSectionHeaderView *headerView = (YXTableSectionHeaderView *)[self.downloadedTableView headerViewForSection:0];
    [headerView updateTaskAmount:YXDownloadedSectionHeader taskAmount:[self.downloadedTableView numberOfRowsInSection:0]];
    
    // update bottom selected number
    [self.yxDelegate selectedCellAmount:self.selectedCellTag.count];
}

- (void)commitSelectingAll {
    self.isSelectAll = !self.isSelectAll;
    [self.selectedCellTag removeAllObjects];
    NSArray *allDownloadedTask = [YXTaskManager getTasksWithStatus:YXTaskStatusDownloaded byTimeline:YES];
    
    for (NSInteger row = 0; row < [self.downloadedTableView numberOfRowsInSection:0]; ++row) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        YXDownloadedTableViewCell *cell = [self.downloadedTableView cellForRowAtIndexPath:indexPath];
        cell.isSelected = YES;
        cell.selectionImageView.highlighted = YES;
        
        // add downloaded task to it
        YXTaskModel *model = allDownloadedTask[row];
        [self.selectedCellTag addObject:[NSString stringWithFormat:@"%@", model.uid]];
    }
    
    [self.yxDelegate selectedCellAmount:self.selectedCellTag.count];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:self.downloadingTableView]) {
        [self isShowDownloadingHitLabel:self.downloadingArray.count == 0];
        return self.downloadingArray.count;
        
    } else {
        [self isShowDownloadedHitLable:self.downloadedArray.count == 0];
        return self.downloadedArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:self.downloadingTableView]) {
        YXDownloadingTableViewCell *downloadingCell = [tableView dequeueReusableCellWithIdentifier:@"YXDownloadingTableViewCell" forIndexPath:indexPath];
        downloadingCell.delegate = self;
        downloadingCell.taskModel = self.downloadingArray[indexPath.row];
        
        return downloadingCell;
        
    } else {
        YXDownloadedTableViewCell *downloadedCell = [tableView dequeueReusableCellWithIdentifier:@"YXDownloadedTableViewCell" forIndexPath:indexPath];
        downloadedCell.taskModel = self.downloadedArray[indexPath.row];
        if (self.isEditing) {
            downloadedCell.selectionImageView.hidden = NO;
            if (self.isSelectAll) {
                downloadedCell.selectionImageView.highlighted = YES;
            }
        }
        return downloadedCell;
    }
}


#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:self.downloadedTableView] && self.isEditing)  {
        YXDownloadedTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        cell.isSelected = !cell.isSelected;
        cell.selectionImageView.highlighted = cell.isSelected;
        
        if (cell.isSelected) {
            [self.selectedCellTag addObject:[NSString stringWithFormat:@"%ld", cell.tag]];
        } else {
            [self.selectedCellTag removeObject:[NSString stringWithFormat:@"%ld", cell.tag]];
        }
        
        [self.yxDelegate selectedCellAmount:self.selectedCellTag.count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 48;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    YXTableSectionHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"YXTableSectionHeaderView"];
    headerView.delegate = self;
    
    if ([tableView isEqual:self.downloadingTableView]) {
        if (!self.isNotification) {
            BOOL isDownloadingTasks = [YXTaskManager getTasksWithStatus:YXTaskStatusDownloading byTimeline:YES].count != 0;
            [headerView setSectionHeaderType:YXDownloadingSectionHeader isDownloadingAll:isDownloadingTasks];
        }
        [headerView updateTaskAmount:YXDownloadingSectionHeader taskAmount:[YXTaskManager getTasksWithStatus:YXTaskStatusDownloading byTimeline:YES].count];
    } else {
        if (!self.isEditing && !self.isNotification) {
            [headerView setSectionHeaderType:YXDownloadedSectionHeader isDownloadingAll:YES];
        }
        [headerView updateTaskAmount:YXDownloadedSectionHeader taskAmount:[tableView numberOfRowsInSection:section]];
    }
    
    return headerView;
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat pageWidth = CGRectGetWidth(scrollView.bounds);
    CGFloat pageFraction = scrollView.contentOffset.x / pageWidth;
    int currentPage = (int)roundf(pageFraction);
    
    // avoid excuting many times when vertical scrolls
    if (scrollView.contentOffset.y == -64) {
        [self.yxDelegate scrollViewDidScrollTo:currentPage];
    }
}


#pragma mark - Lazy Init
- (NSMutableArray *)selectedCellTag {
    if (!_selectedCellTag) {
        _selectedCellTag= [[NSMutableArray alloc] init];
    }
    return _selectedCellTag;
}
- (NSArray *)downloadedArray {
    if (!_downloadedArray) {
        _downloadedArray = [[NSArray alloc] init];
    }
    return _downloadedArray;
}
- (NSArray *)downloadingArray {
    if (!_downloadingArray) {
        _downloadingArray = [[NSArray alloc] init];
    }
    return _downloadingArray;
}
- (UILabel *)downloadingHitLabel {
    if (!_downloadingHitLabel) {
        _downloadingHitLabel = [[UILabel alloc] init];
    }
    return _downloadingHitLabel;
}
- (UILabel *)downloadedHitLabel {
    if (!_downloadedHitLabel) {
        _downloadedHitLabel = [[UILabel alloc] init];
    }
    return _downloadedHitLabel;
}
- (NSArray *)currentDownloadingArray {
    if (!_currentDownloadingArray) {
        _currentDownloadingArray = [[NSArray alloc] init];
    }
    return _currentDownloadingArray;
}
@end
